<template>
    <h-section title="需求受理信息" collapse>
        <div>
            <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                <a-row :gutter="24">
                    <a-col :span="12">
                        <a-form-item label="预计结束时间">
                            <div style="width: 100%">
                                <span>
                                    {{ $filters.dateFilter(form.estimateTime) }}
                                </span>
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" v-if="isShowRepairVersion">
                        <a-form-item label="修复版本">
                            <span v-if="disabled">
                                {{ form.repairVersion }}
                            </span>
                            <a-textarea v-model:value="form.repairVersion" placeholder="请输入版本限制150个字" :maxlength="150" auto-size v-else />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" v-else></a-col>
                    <a-divider />
                    <a-col :span="24">
                        <div class="font-w-b margin-b-8 margin-l-8">方案确认信息</div>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="提交业务方时间">
                            <div style="width: 100%">
                                <span v-if="disabled">{{ $filters.dateFilter(form.submitTime) }}</span>
                                <h-date-picker-cell :disabledDate="false" v-model:value="form.submitTime" v-else />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="业务方确认时间">
                            <div style="width: 100%">
                                <span v-if="disabled">{{ $filters.dateFilter(form.confirmTime) }}</span>
                                <h-date-picker-cell :disabledDate="false" v-model:value="form.confirmTime" v-else />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-divider />
                    <a-col :span="24">
                        <a-form-item label="受理文档">
                            <file-cell v-if="disabled" :fileList="form.selfRequestFiles" />
                            <upload-cell
                                :fileParams="{ connectType: modelName, type: 0 }"
                                :fileList="form.selfRequestFiles"
                                @valueChange="fileChange"
                                v-else
                            >
                                <template #extra>
                                    <div class="caption-font-color">提示：可上传需求落地方案，会议记录等受理相关内容</div>
                                </template>
                            </upload-cell>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" v-if="+detail.stage > 2 && (isSimpleFlow || isSonRequest)">
                        <a-form-item label="审核意见" name="auditOpinion">
                            <div>
                                <div style="white-space: pre-wrap" v-html="form.auditOpinion" v-if="disabled" />
                                <a-textarea
                                    placeholder="请填写需求的可行性分析/必要性分析/方案简述/拒绝原因等限制200个字"
                                    :maxlength="200"
                                    :auto-size="{ minRows: 4 }"
                                    v-model:value="form.auditOpinion"
                                    v-else
                                />
                            </div>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
            <flexbox justify="flex-end" v-if="detail.status === '2' && (isSimpleFlow || isSonRequest)">
                <span style="font-size: 14px" class="caption-font-color">提示： 在需求分析结束后，您可以开始新建产品需求 </span>
            </flexbox>
            <flexbox justify="flex-end" v-if="isShowBtn">
                <flexbox class="btn-group" v-if="isShowAcceptBtn && !isSonRequest">
                    <a-button type="primary" @click="handleSave(1, '否')">拒绝需求</a-button>
                    <a-button type="primary" @click="handleSave(1, '是')">接受需求</a-button>
                    <a-button type="primary" @click="handleZhuanban" v-if="canZhuanban">转办</a-button>
                </flexbox>
                <flexbox class="btn-group" v-if="isShowAcceptBtn && isSonRequest">
                    <a-button type="primary" @click="handleDistribute(5)">拒绝需求</a-button>
                    <a-button type="primary" @click="handleDistribute(4)">接受需求</a-button>
                </flexbox>
                <flexbox class="btn-group" v-if="['1.1', '1.2', '2', '6'].includes(detail.status)">
                    <div v-if="isShowHandleBtn">
                        <a-button type="primary" danger class="margin-l-8" @click="handleUpdate(5)" v-if="detail.status === '6'">废弃</a-button>
                        <a-button type="primary" class="margin-l-8" @click="handleUpdate(2)" v-if="detail.status === '6'">激活</a-button>
                        <a-button type="primary" class="margin-l-8" @click="handleUpdate(6)" v-if="detail.status !== '6'">挂起</a-button>
                    </div>
                    <a-button type="primary" class="margin-l-8" @click="handleSave(2)">保存</a-button>
                </flexbox>
                <!-- 针对已拒绝情况 -->
                <flexbox class="btn-group" v-if="detail.status === '8'">
                    <a-button type="primary" danger @click="handleDelete" v-if="canDelete">删除</a-button>
                    <a-button type="primary" danger class="margin-l-8" @click="handleUpdate(5)" v-if="canDelete">废弃</a-button>
                </flexbox>
            </flexbox>
            <zhuanban-modal ref="zhuanbanModalRef" @success="zhuanbanSuccess" />
        </div>
    </h-section>
</template>

<script lang="ts">
import ZhuanbanModal from './ZhuanbanModal.vue';
import { UploadCell, FileCell, HDatePickerCell } from '@/components';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { FileItem } from '@/types';
import store from '@/store';
import api from '@/api';
import { message } from 'ant-design-vue';
import { useMessage } from '@/hooks/common/useMessage';
import { defineComponent, ref, unref, computed, nextTick, watch, getCurrentInstance } from 'vue';
export default defineComponent({
    components: {
        UploadCell,
        FileCell,
        HDatePickerCell,
        ZhuanbanModal
    },
    props: {
        detail: {
            type: Object,
            default: () => ({})
        },
        disabled: {
            type: Boolean,
            default: false
        },
        modelName: {
            type: String,
            default: ''
        }
    },
    emits: ['save', 'init'],
    setup(props, { emit }) {
        const instance: any = getCurrentInstance();
        const zhuanbanModalRef = ref<any>();
        const { router } = useRouterApi({
            backQuery: {
                path: '/taskRequire/myRequire'
            }
        });
        const ruleFormRef = ref();
        const form = ref<any>({
            referenceTemp: null,
            estimateTime: '',
            selfRequestFiles: [],
            pass: '',
            auditOpinion: '',
            cost: '', //费用
            devCycle: '',
            isNewProject: null, // 是否新项目
            isNeedDev: null, // 是否需要开发
            repairVersion: null,
            confirmTime: '', //确认时间
            submitTime: '', // 提交时间
            agentUser: '',
            agentUserName: ''
        });
        const canZhuanban = computed(() => {
            return new Date(props.detail.createTime).getTime() > new Date('2023-02-01').getTime();
        });
        const rules = computed(() => {
            // 需求初审阶段
            let rules = {};
            // 需求设计阶段
            if (props.detail.stage === '5') {
                rules = {
                    auditOpinion: unref(form).pass === '否' ? [{ required: true, message: '审核意见不能为空', trigger: 'blur', type: 'string' }] : []
                };
            }
            return props.disabled ? {} : rules;
        });
        const isShowRepairVersion = computed(() => {
            // 修复版本显示条件：1.子需求直接显示 2.进行中且没有子需求的需求
            const { status, relateRequest, sonRequestInfos } = props.detail;
            if (relateRequest === 0) {
                if (status === '2') {
                    if (sonRequestInfos && sonRequestInfos.length) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }
            } else {
                return true;
            }
        });
        // 需求受理信息的按钮显示条件：1.非编辑 2.阶段为需求设计 3.系统需求不过规划不拆分或者不是系统需求
        const isShowBtn = computed(() => {
            const { stage, status } = props.detail;
            return (!props.disabled && +stage >= 5) || status === '8';
        });
        const isShowHandleBtn = computed(() => {
            const { relateRequest, isRequireAnalyse, isPlan, isSplit } = props.detail;
            if (relateRequest === 0) {
                return isRequireAnalyse === '否' || (isPlan === '否' && isSplit === '否');
            }
            // 子需求显示
            else {
                return true;
            }
        });
        // 是否是简单流程
        const isSimpleFlow = computed(() => {
            const { isPlan, isSplit, isRequireAnalyse } = props.detail;
            return isRequireAnalyse === '否' || (isPlan === '否' && isSplit === '否');
        });
        const isSonRequest = computed(() => {
            return props.detail.relateRequest > 0;
        });
        const isShowAcceptBtn = computed(() => {
            const { status } = props.detail;
            return status === '1' && (unref(isSimpleFlow) || unref(isSonRequest));
        });
        const canDelete = computed(() => {
            const { status, initiatorEmpId, createUserEmpId } = props.detail;
            const empId = store.getters.userInfo.employeeDTO.empId;
            return status === '8' && (initiatorEmpId === empId || createUserEmpId === empId);
        });
        const validate = () => {
            return new Promise((resolve) => {
                unref(ruleFormRef)
                    .validate()
                    .then(
                        () => {
                            resolve(true);
                        },
                        () => {
                            resolve(false);
                        }
                    );
            });
        };
        const handleSave = (type: number, pass: Nullable<string> = null) => {
            // 先移除所有旧的校验提示
            unref(ruleFormRef).clearValidate();
            // 新的校验会根据pass的值自动生成
            form.value.pass = pass;
            // 暂时先这么写
            nextTick(() => {
                emit('save', type);
            });
        };
        const zhuanbanSuccess = (obj) => {
            form.value.agentUser = obj.agentUser;
            form.value.agentUserName = obj.agentUserName;
            // 先移除所有旧的校验提示
            unref(ruleFormRef).clearValidate();
            // 新的校验会根据pass的值自动生成
            form.value.pass = '转办';
            // 暂时先这么写
            nextTick(() => {
                emit('save', 1);
            });
        };
        // 监听文件删除等操作
        const fileChange = (fileList: FileItem[]) => {
            const files = form.value.selfRequestFiles.filter((item) => item.connectType !== '需求受理信息');
            form.value.selfRequestFiles = [...files, ...fileList];
        };
        // 分发
        const handleDistribute = async (type: number) => {
            const query = {
                type: type.toString(),
                requestInfo: props.detail
            };
            // 新建
            if ([0, 1].includes(type)) {
                query.requestInfo.relateRequest = props.detail.id;
            }
            const { success, errorMsg } = await api.pmpRequestInfoModel.updateSplit(query);
            if (success) {
                if (type === 5) {
                    router.push({
                        path: '/taskRequire/myRequire'
                    });
                } else {
                    instance.proxy.$mitt.emit('updateTaskDetail');
                }
            } else {
                message.error(errorMsg);
            }
        };
        const handleUpdate = async (status) => {
            const query = {
                id: props.detail.id,
                status
            };
            const { success, errorMsg } = await api.pmpRequestInfoModel.updateBusiness(query);
            if (success) {
                message.success('操作成功');
                emit('init');
                if (status !== 2) {
                    router.push({
                        path: '/taskRequire/myRequire'
                    });
                }
            } else {
                message.error(errorMsg);
            }
        };
        const handleZhuanban = () => {
            unref(zhuanbanModalRef).open(props.detail);
        };
        // 删除
        const handleDelete = () => {
            const { createConfirm } = useMessage();
            createConfirm({
                title: '确认删除当前数据？',
                iconType: 'danger',
                onOk: async () => {
                    const query = {
                        id: props.detail.id
                    };
                    const { success, errorMsg } = await api.pmpRequestInfoModel.delete(query);
                    if (success) {
                        message.success('删除成功');
                        router.push({
                            path: '/taskRequire/myRequire'
                        });
                    } else {
                        message.error(errorMsg);
                    }
                }
            });
        };
        const init = () => {
            Object.keys(unref(form)).forEach((key) => {
                const { detail, modelName } = props;
                if (key === 'selfRequestFiles') {
                    if (detail.selfRequestFiles) {
                        form.value.selfRequestFiles = detail.selfRequestFiles.filter((item: FileItem) => item.connectType === modelName);
                    }
                } else {
                    form.value[key] = detail[key];
                }
            });
        };
        init();
        watch(
            () => props.detail.repairVersion,
            (n) => {
                form.value.repairVersion = n;
            },
            { deep: true }
        );
        return {
            zhuanbanModalRef,
            ruleFormRef,
            form,
            canZhuanban,
            rules,
            isShowRepairVersion,
            isShowBtn,
            isShowHandleBtn,
            isShowAcceptBtn,
            isSimpleFlow,
            isSonRequest,
            canDelete,
            validate,
            handleSave,
            fileChange,
            handleDistribute,
            handleUpdate,
            handleZhuanban,
            zhuanbanSuccess,
            handleDelete
        };
    }
});
</script>
<style lang="less" scoped>
.extra-cont {
    margin-left: 12px;
    .extra-box {
        padding: 4px 8px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        color: #505a6e;
        .title {
            margin-left: 8px;
        }
    }
}
button {
    border-radius: 4px;
}
.btn-group {
    margin: 24px 0;
    button + button {
        margin-left: 8px;
    }
}
</style>
